<template>
	<uni-popup ref="popupRef" background-color="#fff" type="bottom" :is-mask-click="!state.paying">
		<uni-section title="支付信息" type="line" v-if="order">
			<uni-card :is-shadow="false" :title="`订单号：${order.order_code}`">
				<view>
					<text>创建时间：</text>
					<text>{{ dayjs(order.created_on).format("YYYY-MM-DD HH:mm:ss") }}</text>
				</view>
				<view>
					<text>商品数量：</text>
					<text>{{ `共计 ${quantity}件`}}</text>
				</view>
				<view>
					<text>支付金额：</text>
					<text style="color: #ee0a24;">{{ `￥${numeral(order.total_price).format("0.00")}` }}</text>
				</view>
			</uni-card>
		</uni-section>
		<button type="primary" style="margin: 0 15px 15px 15px;" :loading="state.paying" @click="payment">
			{{ state.paying?"支付中":"立即支付" }}
		</button>
	</uni-popup>
</template>

<script setup>
	import {
		reactive,
		ref,
		computed
	} from "vue"
	import {
		SERVER_URL
	} from "@/config/index.js"
	import {
		useUserStore
	} from "@/stores/user.js"
	import dayjs from "dayjs"
	import numeral from "numeral"

	const userStore = useUserStore()

	const emits = defineEmits(["paid"])

	const popupRef = ref()

	const state = reactive({
		paying: false
	})

	const order = ref(null)
	const loadOrder = (id) => {
		uni.request({
			url: SERVER_URL + '/customer/order/detail/' + id,
			method: "GET",
			header: {
				"authorization": userStore.token
			},
			success: (res) => {
				if (res.statusCode === 200) {
					order.value = res.data
					if (res.data.payment_status === 1) {
						popupRef.value.open()
					}
				}
			},
		});
	}

	const quantity = computed(() => {
		if (order.value) {
			return order.value.items.reduce((count, item) => {
				count += item.quantity
				return count
			}, 0)
		}

		return 1
	})


	const payment = () => {
		if (!order.value || !order.value.id) return
		state.paying = true
		const fail = () => {
			uni.showToast({
				icon: "fail",
				title: "支付失败"
			})
			state.paying = false
		}
		uni.request({
			url: SERVER_URL + '/customer/order/payment/' + order.value.id,
			method: "PUT",
			header: {
				"content-type": "application/json",
				"authorization": userStore.token
			},
			success: (res) => {
				if (res.statusCode === 200) {
					setTimeout(() => {
						uni.showToast({
							icon: "success",
							title: "支付成功"
						})
						setTimeout(() => {
							popupRef.value.close()
							state.paying = false
							emits("paid")
						}, 800)
					}, 1500)
				} else {
					fail()
				}
			},
			fail: () => {
				fail()
			}
		});
	}

	const handleShow = (id) => {
		state.paying = false
		loadOrder(id)

	}

	defineExpose({
		show: handleShow
	})
</script>

<style scoped lang="scss">

</style>